import 'dart:io';
import 'dart:convert';
import 'package:dio/dio.dart';
import 'package:bot_toast/bot_toast.dart';
import 'package:shared_preferences/shared_preferences.dart';

//redux
import 'package:flutter_app/reducers.dart';

class Utils {
  static String domain = 'http://b2b.nigeriatex.com';

  static request() {
    BaseOptions options = BaseOptions(
      //请求基地址,可以包含子路径
      baseUrl: Utils.domain + '/api', //连接服务器超时时间，单位是毫秒.
      connectTimeout: 5000, //响应流上前后两次接受到数据的间隔，单位为毫秒。
      receiveTimeout: 5000, //Http请求头.
      headers: {
        //do something
        "version": "1.0.0"
      }, //请求的Content-Type，默认值是[ContentType.json]. 也可以用ContentType.parse("application/x-www-form-urlencoded")
      contentType: ContentType.parse(
          "application/json;charset=UTF-8"), //表示期望以那种格式(方式)接受响应数据。接受四种类型 `json`, `stream`, `plain`, `bytes`. 默认值是 `json`,
      responseType: ResponseType.json,
    );

    Dio dio = new Dio(options);

    //拦截
    dio.interceptors
        .add(InterceptorsWrapper(onRequest: (RequestOptions options) async {
      //print("请求之前");
      //options.headers['token'] = '';
      if (options.method == 'GET') {
        options.queryParameters['code'] = 'nt';
        options.queryParameters['lan'] = 'en';
      } else {
        if (options.data == null) {
          options.data = {
            'code': 'nt',
            'lan': 'en',
          };
        } else {
          options.data['code'] = 'nt';
          options.data['lan'] = 'en';
        }
      }

      return options; //continue
    }, onResponse: (Response response) async {
      // 在返回响应数据之前做一些预处理
      if (response.data['code'] != 200) {
        BotToast.showText(text:response.data['msg'],duration: Duration(milliseconds: 1000));
      }
    }, onError: (DioError e) async {
      BotToast.showText(text:'网络错误',duration: Duration(milliseconds: 1000));
      //print('错误');
    }));

    return dio;
  }

  static setLocaleData(key, value) async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    if (value is String) {
      prefs.setString(key, value);
    } else {
      prefs.setString(key, jsonEncode(value));
    }
  }

  static getLocaleData(key) async {
    SharedPreferences prefs = await SharedPreferences.getInstance();

    if (prefs.getString(key) != null) {
      try {
        return jsonDecode(prefs.getString(key));
      } catch (e) {
        return prefs.getString(key);
      }
    } else {
      return null;
    }
  }

  static delLocaleData(key) async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    prefs.remove(key);
  }

  static login(store, params) {
    //全局保存登录信息
//    print(params['User']);
    if (params['Ticket'] != null && params['User'] != null) {
      //持久化登录信息
      Utils.setLocaleData('Ticket', params['Ticket']);
      Utils.setLocaleData('User', params['User']);
    
      store.dispatch(new LoginSuccessAction(
          Ticket: params['Ticket'], User: params['User'])
      );
    }else{
      store.dispatch(new InitStatus());
    }
  }

  static logout(store) async {
    //后台退出
    var response = await Utils.request().get('/WebUser/Logout');
    if (response.data['code'] == 200) {
      //app退出
      store.dispatch(Actions1.LogoutSuccess);
      //清除持久化的用户信息
      Utils.delLocaleData('Ticket');
      Utils.delLocaleData('User');
    }
  }
}
